package com.sys.db.ibatis.dbc;

import java.io.Reader;
import java.sql.SQLException;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.sqlmap.client.SqlMapSession;

public class SqlMapSessionFactory {
	private static String CONFIG_FILE_LOCATION = "SqlMapConfig.xml";
	private static final ThreadLocal<SqlMapSession> threadLocal = new ThreadLocal<SqlMapSession>();
	private static SqlMapClient client;
	private static String configFile = CONFIG_FILE_LOCATION;

	static {
		try {
			Reader reader = Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
			client = SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	private SqlMapSessionFactory() {
	}

	public static SqlMapSession getSession() throws SQLException {
		SqlMapSession session = (SqlMapSession) threadLocal.get();

		if (session == null || session.getCurrentConnection() == null
				|| session.getCurrentConnection().isClosed()) {
			session = client.openSession();
			threadLocal.set(session);
		}

		return session;
	}


	public static void closeSession() {
		SqlMapSession session = (SqlMapSession) threadLocal.get();
		threadLocal.set(null);

		if (session != null) {
			session.close();
		}
	}

}
